package com.brid.server;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RestController;

import java.util.Properties;
import java.util.concurrent.Future;


/**
 * @Author: 司军强
 * @Date: 19:48 2019/12/18
 * @Description: 测试连接kfka
 */
@RestController
@Slf4j
public class KfkaProducer {
    //kfka对外提供的集群地址
    private static final String BROKERLIST = "192.168.223.128:9092";
    //topic 的name
    private static final String TOPIC = "hema";



    public static void main(String[] args) {
        //添加必要的配置
        Properties properties = new Properties();
        //设置key序列化器
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        //设置values序列化q
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        //设置重试次数
        properties.put(ProducerConfig.RETRIES_CONFIG, 10);
        //设置集群地址
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, BROKERLIST);
////////////////////////////////////////////////////////////////////////////////////////////////
        //创建kafkaProducer对象 准备生产消息
        KafkaProducer producer = new KafkaProducer<>(properties);
        //创建一个消息 并指定topic 和 key 和value
        ProducerRecord record = new ProducerRecord<>(TOPIC, "kafka-demo-001", "this is my first kafka");
        //发送消息
        try {
            Future send = producer.send(record);
            log.info("【push message success】 send to topic-{} message-{}", TOPIC, JSONObject.toJSON(send));
        } catch (Exception e) {
            log.error("【push message failure】 meeage-{}", e);
        }


    }


}
